package com.grass.finding.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpUtil {

    /**
     * 请求某一个url的响应体
     * @param url 要请求的地址
     * @return
     */
    public static  String doGet(String url){
        HttpURLConnection connection = null;
        StringBuffer res = new StringBuffer();
        InputStream is = null;
        BufferedReader bufferedReader = null;
        try {
            //建立连接
            URL realUrl = new URL(url);
            connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(1000);
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200){
                //返回的数据
                is = connection.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                String temp = null;
                while((temp = bufferedReader.readLine()) != null){
                    res.append(temp);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (null != bufferedReader){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
//            关闭连接
            connection.disconnect();
        }
        return res.toString();
    }
}
